package com.tanhua.admin.listeners;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    @RabbitListener(
            bindings= @QueueBinding(
                    value = @Queue(
                            name = "tanhua.log.queue",
                            durable = "true"
                    ),
                    exchange = @Exchange(
                            name = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.*"
            )
    )
    public void log(String message) {
        System.out.println("获取日志消息："+message);
        Map<String,String> map = JSON.parseObject(message, Map.class);
        //1、获取消息内容   userId，type，logTime
        Long userId = Long.valueOf(map.get("userId"));
        String type = map.get("type");
        String logTime = map.get("logTime");
        //2、创建Log对象
        Log log = new Log();
        log.setUserId(userId);
        log.setLogTime(logTime);
        log.setType(type);
        //3、保存到数据库中
        logMapper.insert(log);
    }
}
